package LeetCode.leetcode106;

public class Review1 {

    public static TreeNode buildTree(int[] inorder, int[] postorder) {
        return test(inorder,postorder);
    }
    public static TreeNode test(int[] inorder,int[] postorder){
        if (postorder.length == 0) return null;
        int v = postorder[postorder.length - 1];
        TreeNode node = new TreeNode(v);
        if (postorder.length == 1) return node;
        int index = 0;
        for (; index < inorder.length; index++) {
            if (inorder[index] == v) break;
        }
        //左边数组
        int[] inorderL = new int[index];
        int[] postorderL = new int[index];
        for (int i = 0; i < index; i++) {
            inorderL[i] = inorder[i];
        }
        for (int i = 0; i < index; i++) {
            postorderL[i] = postorder[i];
        }
        //右边数组
        int[] inorderR = new int[inorder.length - index - 1];
        int[] postorderR = new int[inorder.length - index - 1];
        for (int i = index + 1,j = 0; i < inorder.length - 1; i++,j++) {
            inorderR[j] = inorder[i];
        }
        for (int i = index + 1,j = 0; i < postorder.length - 1; i++,j++) {
            postorderR[j] = postorder[i];
        }
        node.left = test(inorderL,postorderL);
        node.right = test(inorderR,postorderR);
        return node;
    }
}